package com.binguo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.binguo.api.baidu.BaiduRecUtil;
import com.binguo.api.baidu.localrec.ResResult;
import com.binguo.api.form.OrderForm;
import com.binguo.api.huawei.imagesearch.model.RecResult;
import com.binguo.api.imgrec.ImgRecResult;
import com.binguo.api.result.Result;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.api.schedule.ScheduleService;
import com.binguo.api.service.GroovyService;
import com.binguo.api.service.SpringUtil;
import com.binguo.api.service.api.ShopApiInterface;
import com.binguo.api.transfer.OrderFormTransfer;
import com.binguo.common.enums.CardType;
import com.binguo.common.enums.ProductStorageType;
import com.binguo.common.util.FileDownloader;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.common.util.JsonUtil;
import com.binguo.helper.FaceHelperV3;
import com.binguo.model.api.dto.OrderDTO;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.AdvertRepository;
import com.binguo.model.repository.CustomerRepository;
import com.binguo.model.repository.PayCardRepository;
import com.binguo.model.repository.ProductRepository;
import com.binguo.service.YunPengCustomerService;
import com.binguo.yprecapi.YpRecService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import tk.mybatis.mapper.entity.Condition;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.stream.Collectors;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RestController
public class TestController {

    @Resource
    PayCardMapper payCardMapper;

    @Autowired
    PayCardRepository payCardRepository;

    @Resource
    FaceMapper faceMapper;


    @Resource
    LogProductImgFromUserMapper logProductImgFromUserMapper;

    @Resource
    LogProductImgMapper logProductImgMapper;


    @Autowired
    BaiduRecUtil baiduRecUtil;
    @Autowired
    DataLoadService dataLoadService;

    @Resource
    ShopBaiduUrlMapper shopBaiduUrlMapper;

    @Resource
    ShopBaiduUrlCurMapper shopBaiduUrlCurMapper;

    @Resource
    ShopProductRefMapper shopProductRefMapper;
    @Resource
    CustomerMapper customerMapper;
    @Resource
    CustomerRepository customerRepository;
    @Resource
    CustomerExtendMapper customerExtendMapper;
    @Resource
    BranchMapper branchMapper;

    @Resource
    ProductMapper productMapper;


    @Autowired
    OrderFormTransfer orderFormTransfer;


    @Autowired
    GroovyService groovyService;

    public static void main2(String[] args) {

        String s = "{\n" +
                "response: {\n" +
                "13817246599: {\n" +
                "detail: {\n" +
                "area: [\n" +
                "{\n" +
                "city: \"上海\"\n" +
                "}\n" +
                "],\n" +
                "province: \"上海\",\n" +
                "type: \"domestic\",\n" +
                "operator: \"移动\"\n" +
                "},\n" +
                "location: \"上海上海移动\"\n" +
                "}\n" +
                "},\n" +
                "responseHeader: {\n" +
                "status: 200,\n" +
                "time: 1581846360885,\n" +
                "version: \"1.1.0\"\n" +
                "}\n" +
                "}";

        if (s.contains("city")) {
            int a = s.indexOf("city");


            System.out.println(s.substring(a + 7
                    , a + 13));

            String b = s.substring(a + 7
                    , a + 13);


            int a2 = b.indexOf("\"");
            String c = b.substring(0, a2);

            System.out.println(c);
        }
        if(true){
            return;
        }
        try {
            FileReader fileReader = new FileReader("/Users/jay/IdeaProjects/binguo/api/target/ccc");

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = bufferedReader.readLine();

            List<String> cardNoList = new ArrayList<>();
            while (line != null && StringUtils.hasText(line)) {
                cardNoList.add(line);
                System.out.println(line + ",");
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {

        }
    }

    @Resource
    AdvertRepository advertRepository;
    @Resource
    WxTempUserMapper wxTempUserMapper;
    @Resource
    LogProductRecMapper logProductRecMapper;

    @Resource
    YpRecService ypRecService;
    @Resource
    ProductRepository productRepository;
    @Resource
    ProductInventoryMapper productInventoryMapper;
    @Resource
    YunPengCustomerService yunPengCustomerService;
//    @Resource
    ScheduleService scheduleService;


    public HttpHeaders DEFAULT_JSON_HEADER_UTF8;

    public static void main(String[] args) {
        /*String a = "http://106.54.0.219:8019/images/source/199/32b416bd-2275-4559-9ef9-bfbf3e59dcc4.png";
        String[] b = a.split("/");

        System.out.println(b[b.length - 1]);*/






    }


    @GetMapping(value = "/api/aabbcc", produces = APPLICATION_JSON_VALUE)
    public String adfasdfaadsf() throws Exception{
//        yunPengCustomerService.addIntranetFace2();
        return "okk";
    }


    @GetMapping(value = "/api/jaybb", produces = APPLICATION_JSON_VALUE)
    public String adfasdfadsf() throws Exception{

        Condition condition = new Condition(Product.class);
        condition.or().andEqualTo("shopid", 199)
                .andEqualTo("deleted", false)
                .andEqualTo("productType", 2)
        ;

        List<Product> productList = productMapper.selectByCondition(condition);

        for (Product temp : productList) {
            LogProductImg logProductImg = new LogProductImg();
            logProductImg.setProductId(temp.getId());

            logProductImg.setSourceImg(temp.getProductpic());

            logProductImgMapper.insertSelective(logProductImg);
        }


        return "ok";
    }


//    @GetMapping(value = "/api/jayaa", produces = APPLICATION_JSON_VALUE)
    public String baisui() throws Exception{

        Condition condition = new Condition(Product.class);
        condition.or().andEqualTo("shopid", 199)
                .andEqualTo("deleted", false)
                .andEqualTo("productType", 1)
        ;

        List<Product> productList = productMapper.selectByCondition(condition);

        for (Product temp : productList) {
            Product product = new Product();
            product.setShopid(temp.getShopid());
            product.setCreated(new Date());
            product.setName(temp.getName());
            product.setPrice(temp.getPrice());
            product.setDeleted(false);
            product.setMinorcategoryid(product.getMajorcategoryid());
            product.setVipprice(temp.getVipprice());
            product.setStatus(new Byte("2"));
            product.setSearchcode(System.currentTimeMillis() + "");
            product.setProductType(2);
            product.setStoreid(219);

            Condition tempCondition = new Condition(LogProductImg.class);
            tempCondition.or().andEqualTo("productId", temp.getId())
                        .andEqualTo("baiduDeleted", 0)
            ;
            List<LogProductImg> logProductImgs = logProductImgMapper.selectByCondition(tempCondition);

            if (logProductImgs != null && logProductImgs.size() > 0) {
                product.setProductpic(logProductImgs.get(0).getImgCutNetUrl());
            }else {
                Condition tempCondition2 = new Condition(LogProductImgFromUser.class);
                tempCondition2.or().andEqualTo("productId", temp.getId())
                        .andEqualTo("baiduDeleted", 0)
                ;
                List<LogProductImgFromUser> logProductImgFromUsers = logProductImgFromUserMapper.selectByCondition(tempCondition2);
                if (logProductImgFromUsers != null && logProductImgFromUsers.size() > 0) {
                    product.setProductpic(logProductImgFromUsers.get(0).getImgCutNetUrl());
                }
            }

            productRepository.save(product);

            ProductInventory tempProductInventory = new ProductInventory();

            tempProductInventory.setProductId(product.getId());
            tempProductInventory.setBreakfastGeneralSum(1);
            tempProductInventory.setBraekfastSum(0);
            tempProductInventory.setLunchGeneralSum(1);
            tempProductInventory.setLunchSum(0);
            tempProductInventory.setDinnerGeneralSum(1);
            tempProductInventory.setDinnerSum(0);
            tempProductInventory.setStandard("份");

            productInventoryMapper.insertSelective(tempProductInventory);
        }


        return "ok";
    }

    @GetMapping(value = "/api/testa", produces = APPLICATION_JSON_VALUE)
    public String changeProductToLocal2() throws Exception{

        DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);

        Condition condition = new Condition(LogProductRec.class);
        condition.setOrderByClause(" id desc limit 400");
//        condition.or().andEqualTo("shopId", 199)
        condition.or().andEqualTo("shopId", 160)
        ;
        List<LogProductRec> logProductRecList = logProductRecMapper.selectByCondition(condition);

        for (LogProductRec logProductRec : logProductRecList) {

            String[] b = logProductRec.getImgSrcNetUrl().split("/");
            String filePath = "/Users/jay/Downloads/0428/" + b[b.length - 1];
            FileDownloader.downloadNet(logProductRec.getImgSrcNetUrl(),filePath);

            String content = ImageBase64Util.getImageBinary(filePath);


            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
            Map<String, String> param = new HashMap<>();
            param.put("fileContent", content);
            param.put("shopId", "236");
            param.put("deviceId", "30:9C:23:4B:08:45");
            String jsonParam = JsonUtil.toJson(param);

            HttpEntity entity = new HttpEntity<>(jsonParam, DEFAULT_JSON_HEADER_UTF8);

            ResponseEntity<String> resp = restTemplate.postForEntity("http://111.229.73.150:9095/api/product/recWithLocation", entity, String.class);
            String result = resp.getBody();
            System.out.println(result);
            JSONObject json = JSONObject.parseObject(result);

            JSONObject obj = json.getObject("data", JSONObject.class);
            String imgUrl = obj.getString("imgUrl");

            String filePath2 = "/Users/jay/Downloads/0430/" + System.currentTimeMillis() + ".png";
            FileDownloader.downloadNet(imgUrl, filePath2);

        }


        return "ok";
    }
    @GetMapping(value = "/api/changeProductToLocal", produces = APPLICATION_JSON_VALUE)
    public String changeProductToLocal() {

        Condition condition = new Condition(LogProductImgFromUser.class);
        condition.or().andEqualTo("shopId", 220)
                      .andEqualTo("baiduDeleted", 0)
                      .andEqualTo("fromCorrect", 0)
        ;
        List<LogProductImgFromUser> logProductImgFromUsers = logProductImgFromUserMapper.selectByCondition(condition);

        for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUsers) {

            ypRecService.addProductImg(logProductImgFromUser.getImgCutNetUrl(), logProductImgFromUser.getProductId(), 240, "122.51.20.127:5001");
        }


        return "ok";
    }

    @GetMapping(value = "/api/cc", produces = APPLICATION_JSON_VALUE)
    public String c() {

        Condition condition = new Condition(CustomerExtend.class);
        condition.or().andEqualTo("shopId", 148);

        List<CustomerExtend> customerExtendList = customerExtendMapper.selectByCondition(condition);

        List<String> phoneList = new ArrayList<>();
        List<Integer> customerIdList = new ArrayList<>();
        for (CustomerExtend customerExtend : customerExtendList) {
            customerIdList.add(customerExtend.getCustomerId());
        }

        String customerIdListStr = org.apache.commons.lang3.StringUtils.join(customerIdList.toArray(), ",");
        List<Customer> customerList = customerMapper.selectByIds(customerIdListStr);

        for (Customer customer : customerList) {
            if (StringUtils.hasText(customer.getPhone())) {
                phoneList.add(customer.getPhone());

                Customer temp = new Customer();
                temp.setId(customer.getId());
//                temp.setPhone("148_" + customer.getPhone());
                temp.setOpenid("");
                customerMapper.updateByPrimaryKeySelective(temp);
            }
        }




        /*Condition wxUserCondition = new Condition(WxTempUser.class);
        wxUserCondition.or().andIn("phone", phoneList);

        wxTempUserMapper.deleteByCondition(wxUserCondition);*/

        return "ok";
    }


    @GetMapping(value = "/api/k", produces = APPLICATION_JSON_VALUE)
    public String k() {


        List<Integer> productIdList = new ArrayList<>();
        productIdList.add(10609);
        productIdList.add(10568);
        productIdList.add(10161);
        productIdList.add(9524);
        productIdList.add(8750);
        productIdList.add(10156);
        productIdList.add(7564);
        productIdList.add(5926);

        Condition condition = new Condition(LogProductImgFromUser.class);
        condition.or().andIn("productId", productIdList);

        List<LogProductImgFromUser> logProductImgFromUserList = logProductImgFromUserMapper.selectByCondition(condition);

        for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
            if (StringUtils.hasText(logProductImgFromUser.getImgCutNetUrl())) {
                if (logProductImgFromUser.getImgCutNetUrl().startsWith("http")) {
                    String productPath = "/Users/jay/PycharmProjects/yprecapi/data/" + logProductImgFromUser.getProductId();
                    File shopFile = new File(productPath);

                    if (!shopFile.exists()) {
                        shopFile.mkdir();
                    }

                    String filename = "/Users/jay/PycharmProjects/yprecapi/data/" + logProductImgFromUser.getProductId()
                            + "/" + UUID.randomUUID() + ".png";

                    FileDownloader.downloadNet(logProductImgFromUser.getImgCutNetUrl(), filename);
                }
            }
        }



        return "ok";
    }


    @GetMapping(value = "/api/b", produces = APPLICATION_JSON_VALUE)
    public String b() {

        ResponseEntity<String> responseEntity = new RestTemplate().getForEntity("", String.class, new HashMap<>());
        String body = responseEntity.getBody();
        if (body.contains("city")) {

        }
        try {
            FileReader fileReader = new FileReader("/Users/jay/IdeaProjects/binguo/api/target/aaa");

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = bufferedReader.readLine();

            List<String> cardNoList = new ArrayList<>();
            Map<String, String> cardNoNameMap = new LinkedHashMap<>();
            while (line != null && StringUtils.hasText(line)) {

                String[] a = line.split(",");
                String cardNo = a[0];
                String username = a[1];

                cardNoNameMap.put(cardNo, username);
                cardNoList.add(cardNo);
                System.out.println(line);
                line = bufferedReader.readLine();


            }
            Condition condition = new Condition(PayCard.class);
            condition.or().andIn("cardno", cardNoList);
            List<PayCard> payCardList = payCardRepository.findByCondition(condition);

            List<String> dbCardNoList = payCardList.stream().map(PayCard::getCardno).collect(Collectors.toList());

            cardNoList.removeAll(dbCardNoList);

            List<String> errorCardsList = new ArrayList<>();
            List<String> rightCardsList = new ArrayList<>();
            for (PayCard payCard : payCardList) {
                Integer customerId = payCard.getCustomerid();
                Customer customer = customerMapper.selectByPrimaryKey(customerId);
                if (!customer.getName().equals(cardNoNameMap.get(payCard.getCardno()))) {
                    System.out.println(payCard.getCardno() + "," + customer.getName());
                    errorCardsList.add(payCard.getCardno());
                }else {
                    rightCardsList.add(customerId.toString());
//                    rightCardsList.add(payCard.getCardno());
                }
            }

            if (cardNoList.size() > 0) {
                System.out.println(cardNoList);
                for (String cardNo : cardNoList) {
                    String username = cardNoNameMap.get(cardNo);
                    Condition customerCondition = new Condition(Customer.class);
                    customerCondition.or().andEqualTo("name", username);
                    List<Customer> customerList = customerMapper.selectByCondition(customerCondition);

                    if (customerList != null && customerList.size() > 0) {
                        Customer customer = customerList.get(0);

                        Integer customerId = customer.getId();

                        Condition paycardCondition = new Condition(PayCard.class);
                        paycardCondition.or().andEqualTo("customerid", customerId);
                        List<PayCard> payCards = payCardRepository.findByCondition(paycardCondition);
                        if (payCards != null && payCards.size() > 0) {
                            System.out.println("new cards =" + payCards.get(0).getCardno());
                            rightCardsList.add(payCards.get(0).getCustomerid().toString());
//                            rightCardsList.add(payCards.get(0).getCardno());
                        }

                    }else {
                        System.out.println("error" + cardNo + ": name=" + cardNoNameMap.get(cardNo));
                    }
                }

                System.out.println(rightCardsList.size());

                FileWriter fileWriter = new FileWriter("/Users/jay/IdeaProjects/binguo/api/target/bbb");

                for (String s : rightCardsList) {
                    fileWriter.write(s);
                    fileWriter.write("\r\n");
                }
                fileWriter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }


    @GetMapping(value = "/api/c", produces = APPLICATION_JSON_VALUE)
    public String ccccc(@RequestParam Integer oldShopId, @RequestParam Integer newShopId) {

        try {
            Condition condition = new Condition(Product.class);
            condition.or().andEqualTo("shopid", oldShopId);
            List<Product> productList = productMapper.selectByCondition(condition);


            Condition branchCondition = new Condition(Branch.class);

            branchCondition.or().andEqualTo("shopId", newShopId);
            List<Branch> branch = branchMapper.selectByCondition(branchCondition);
            Integer branchId = branch.get(0).getBranchId();

            for (Product product : productList) {
                Product newP = new Product();

                BeanUtils.copyProperties(product, newP);

                newP.setId(null);
                newP.setShopid(newShopId);

                newP.setCreated(new Date());
                newP.setStoreid(branchId);

                productMapper.insertSelective(newP);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "/api/a", produces = APPLICATION_JSON_VALUE)
    public String aaaa() {

        try {
            scheduleService.eraseShopBaiduUrlCur();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "/api/st", produces = APPLICATION_JSON_VALUE)
    public String ta() {

        Condition condition = new Condition(Advert.class);
        condition.or().andEqualTo("id", 37);

        Advert advert = new Advert();
        advert.setShopId(0);
        advertRepository.updateByCondition(advert, condition);

        return "ok";
    }

    @GetMapping(value = "/api/s", produces = APPLICATION_JSON_VALUE)
    public String t() {

        try {
            FileReader fileReader = new FileReader("/Users/jay/IdeaProjects/binguo/api/target/user");

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = bufferedReader.readLine();

            List<Map<String, String>> tempList = new ArrayList<>();
            while (line != null && StringUtils.hasText(line)) {
                String[] ar = line.split(",");

                System.out.println(ar[0]);
                System.out.println(ar[2]);
                System.out.println(ar[1]);
                Map<String, String> tempMap = new HashMap<>();
                tempMap.put("username", ar[0]);
                tempMap.put("cardNo", ar[2]);
                tempList.add(tempMap);

                line = bufferedReader.readLine();
            }

            Condition condition = new Condition(PayCard.class);
            condition.or().andEqualTo("shopid", 51)
            ;
            List<PayCard> payCardList = payCardRepository.findByCondition(condition);

            List<Customer> customerList = null;
            List<String> customerNameList = null;
            List<String> payCardNoList = null;
            Map<String, Integer> customerNameIdMap = new HashMap<>();
            if (payCardList != null) {
                List<Integer> customerIdList =
                        payCardList.stream().map(PayCard::getCustomerid).collect(Collectors.toList());

                Condition customerCondition = new Condition(Customer.class);
                customerCondition.or().andIn("id", customerIdList);
                customerList = customerMapper.selectByCondition(customerCondition);

                customerNameList = customerList.stream().map(Customer::getName).collect(Collectors.toList());
                customerNameIdMap = customerList.stream().collect(Collectors.toMap(Customer::getName, Customer::getId));

                payCardNoList = payCardList.stream().map(PayCard::getCardno).collect(Collectors.toList());
            }

            Map<String, List<String>> nameImgMap = new HashMap<>();
            try {
                File f = new File("/Users/jay/IdeaProjects/binguo/api/target/aaaa");

                File[] files = f.listFiles();
                for (File temp : files) {
                    System.out.println(temp.getName());
                    List<String> imgList = nameImgMap.get(temp.getName());
                    if (imgList == null) {
                        imgList = new ArrayList<>();
                    }
                    imgList.add("http://popecash.com/51/" +  URLEncoder.encode(temp.getName()));
                    nameImgMap.put(temp.getName(), imgList);
                }
            } catch (Exception e) {

            }

            for (Map<String, String> map : tempList) {
                String username = map.get("username");
                String cardNo = map.get("cardNo");

                List<String> imgList = new ArrayList<>();

                for (Map.Entry<String, List<String>> entry : nameImgMap.entrySet()) {
                    String key = entry.getKey();
                    if (key.contains(username)) {
                        imgList.addAll(entry.getValue());
                    }
                }
                if (imgList.size() == 0) {
                    continue;
                }

                Integer cardNoInt = Integer.valueOf(cardNo);
                if (cardNoInt <= 0) {
                    continue;
                }

                if (payCardNoList.contains(cardNo)) {
                    System.out.println(username);
                    System.out.println(cardNo);
                }


                //已存在用户
                if (customerNameList.contains(username)) {
                    System.out.println(username);
                    System.out.println(cardNo);


                    Integer customerId = customerNameIdMap.get(username);
                    Condition payCardCondition = new Condition(PayCard.class);
                    payCardCondition.or().andEqualTo("shopid", 51)
                                .andEqualTo("deleted", false)
                                .andEqualTo("cardno", cardNo)

                    ;
                    List<PayCard> tempPayCardList =
                            payCardRepository.findByCondition(payCardCondition);

                    if (tempPayCardList != null && tempPayCardList.size() > 0) {
                        continue;
                    }else {

                        creadPayCard(customerId, cardNo, username);
                    }
                    addFace(customerId, imgList);
                    continue;
                }else {
                    Integer customerId = createCustomer(username);
                    creadPayCard(customerId, cardNo, username);
                    addFace(customerId, imgList);
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }

        return "ok";
    }

    long phone = 29900000001l;
    private Integer createCustomer(String username){
        Customer customer = new Customer();
        customer.setName(username);
        customer.setPhone("" + phone);
        customerRepository.save(customer);

        Integer customerId = customer.getId();

        CustomerExtend customerExtend = new CustomerExtend();
        customerExtend.setGroupId(0);
        customerExtend.setGroupName("普通会员");
        customerExtend.setIsAudit(1);
        customerExtend.setCustomerId(customerId);
        customerExtend.setShopId(51);
        customerExtend.setUserStatus(1);
        customerExtendMapper.insertSelective(customerExtend);

        phone++;
        return customerId;
    }

    private void creadPayCard(Integer customerId, String cardNo, String username){
        PayCard payCard = new PayCard();
        payCard.setCustomerid(customerId);
        payCard.setShopid(51);
        payCard.setCardtype(CardType.BINGUO_CARD.getCode().byteValue());
        payCard.setName("金义都市管委会餐厅卡");
        payCard.setIsmaster(true);
        payCard.setYktAccountbalance(0l);
        payCard.setAccountbalance(0l);
        payCard.setWxAccountbalance(0l);
        payCard.setBzAccountbalance(0l);
        payCard.setDeleted(false);
        payCard.setCreated(new Date());
        payCard.setUpdated(new Date());
        payCardRepository.save(payCard);

        PayCard tempPayCard = new PayCard();
        tempPayCard.setId(payCard.getId());
        tempPayCard.setCardno(payCard.getId() + "");
        payCardMapper.updateByPrimaryKeySelective(tempPayCard);

        PayCard realPayCard = new PayCard();
        realPayCard.setCustomerid(customerId);
        realPayCard.setShopid(51);
        realPayCard.setCardno(cardNo);
        realPayCard.setCardtype(CardType.YKT_CARD.getCode().byteValue());
        realPayCard.setName(username + "的一卡通");
        realPayCard.setIsmaster(false);
        realPayCard.setYktAccountbalance(0l);
        realPayCard.setAccountbalance(0l);
        realPayCard.setWxAccountbalance(0l);
        realPayCard.setBzAccountbalance(0l);
        realPayCard.setDeleted(false);
        realPayCard.setCreated(new Date());
        realPayCard.setUpdated(new Date());
        payCardRepository.save(realPayCard);
    }

    private void addFace(Integer customerId, List<String> imgList){
        int i=0;
        for (String img : imgList) {
            String faceId = null;
            if (i==0) {
                try {

                    faceId = FaceHelperV3.createPerson("51", 51 + "_" + customerId, img);
                } catch (Exception e) {
                    faceId = FaceHelperV3.addFace(51 + "_" + customerId, img);
                }
            }else {
                faceId = FaceHelperV3.addFace(51 + "_" + customerId, img);
            }

            Face face = new Face();
            face.setPersionid(51 + "_" + customerId);
            face.setFaceurl(img);
            face.setCustomerId(customerId);
            face.setFaceid(faceId);
            face.setCreateTime(new Date());
            face.setIsDeleted(0);
            faceMapper.insertSelective(face);
        }
    }

    @GetMapping(value = "/api/baidu", produces = APPLICATION_JSON_VALUE)
    public String baidu() {
        try {
            FileReader fileReader = new FileReader("/Users/jay/IdeaProjects/binguo/api/target/a");

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = bufferedReader.readLine();

            List<Map<String, String>> tempList = new ArrayList<>();
            while (line != null && StringUtils.hasText(line)) {
                String[] ar = line.split(",");

                System.out.println(ar[0]);
                System.out.println(ar[1]);
                System.out.println(ar[2]);
                Map<String, String> tempMap = new HashMap<>();
                tempMap.put("appid", ar[0]);
                tempMap.put("appkey", ar[1]);
                tempMap.put("security", ar[2]);
                tempList.add(tempMap);

                line = bufferedReader.readLine();
            }

            for (Map<String, String> t : tempList) {
                String appid = t.get("appid");
                String appkey = t.get("appkey");
                String security = t.get("security");


                ShopBaiduUrlCur shopBaiduUrl = new ShopBaiduUrlCur();
                shopBaiduUrl.setBaiduUrl("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/caipin2");
                shopBaiduUrl.setAppid("16820888");
                shopBaiduUrl.setApiKey("ROsdsvgElTjYWTjpiQ1Nh2pz");
                shopBaiduUrl.setSecurityKey("lxfzodzy6K6KmzXDkmnKzDveXBNFUdM5");
                shopBaiduUrl.setUrlType(1);
                shopBaiduUrl.setUsed(0);

                shopBaiduUrlCurMapper.insertSelective(shopBaiduUrl);

                ShopBaiduUrlCur shopBaiduUrl2 = new ShopBaiduUrlCur();
                shopBaiduUrl2.setAppid(appid);
                shopBaiduUrl2.setApiKey(appkey);
                shopBaiduUrl2.setSecurityKey(security);
                shopBaiduUrl2.setUrlType(2);
                shopBaiduUrl2.setUsed(0);

                shopBaiduUrlCurMapper.insertSelective(shopBaiduUrl2);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }


    @GetMapping(value = "/api/refresh", produces = APPLICATION_JSON_VALUE)
    public String refresh() {
        try {
            dataLoadService.loadData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "/api/groovy/refresh", produces = APPLICATION_JSON_VALUE)
    public String groovyRefresh() {
        try {
            groovyService.reload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping(value = "/api/jay", produces = APPLICATION_JSON_VALUE)
    public String test() throws Exception{
/*
        String url = "http://152.136.46.212:8099/sendMsg";
        Integer shopId = 23;

        Map<String, String> param = new HashMap<>();
        param.put("shopId", "23");
        param.put("imgUrl", "http://img.binguoai.com/20190430_150830_8.jpg");


        try {
            String jsonParam = JsonUtil.toJson(param);

            HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
            MediaType jsontype = MediaType.APPLICATION_JSON_UTF8;
            DEFAULT_JSON_HEADER.setContentType(jsontype);

            HttpEntity entity = new HttpEntity<>(jsonParam, DEFAULT_JSON_HEADER);

            ResponseEntity<String> recImgResult = new RestTemplate().postForEntity(url, entity, String.class);

            String result = recImgResult.getBody();

            System.out.println(result);
            result = result.substring(result.indexOf("{"));
            ImgRecResult resResult = JsonUtil.parse(result, ImgRecResult.class);


            System.out.println(resResult.getNumber());
        } catch (IOException e) {
            e.printStackTrace();
        }*/


//        baiduRecUtil.addImg(135, "/Users/jay/Downloads/WechatIMG708.png", "135_8681", 104);
//
//        RecResult result = new RecResult();

//        baiduRecUtil.addImg(163, "/Users/jay/Downloads/075befac-d9dc-4ee8-b428-985825b4cad4_cut1.png", "163_8957", 124);
//        baiduRecUtil.addImg(135, "/Users/jay/Downloads/075befac-d9dc-4ee8-b428-985825b4cad4_cut1.png", "135_8289", 104);
//        baiduRecUtil.delImg("2681205172,1850767285", 135, 104);
//        baiduRecUtil.delImg("4124897993,4273536844", 135, 104);
//        baiduRecUtil.delImg("3101669540,3318942043", 135, 104);
//        baiduRecUtil.delImg("3034788708,3202844627", 148, 87);
//        baiduRecUtil.delImg("1662295014,515921620", 135, 104);
//        baiduRecUtil.delImg("2788643516,1287883869", 148, 87);
//        baiduRecUtil.delImg("2404633112,1657600874", 135, 104);
//        baiduRecUtil.delImg("2578774538,739495609", 135, 104);
//        baiduRecUtil.delImg("2320995966,1427735609", 164, 125);
//        baiduRecUtil.delImg("3414379173,4185237998", 164, 125);
//        baiduRecUtil.delImg("3020079888,2324418955", 164, 125);
//        baiduRecUtil.delImg("1645078146,1045259034", 164, 125);
        baiduRecUtil.delImg("2041139700,936012353", 23, 9);
        baiduRecUtil.delImg("261189869,1222901162", 184, 9);

        return "ok";
    }

    @GetMapping(value = "/api/ttest", produces = APPLICATION_JSON_VALUE)
    public String getInitCode(String a) {
        Condition condition = new Condition(PayCard.class);
        condition.or().andEqualTo("cardno", "123")
                .andEqualTo("shopid", "23")
                .andEqualTo("cardtype",CardType.YKT_CARD.getCode().byteValue());

//        condition.getOredCriteria().get(0).andEqualTo()
        Optional<PayCard> payCardOptional = payCardRepository.findByCondition(condition).stream().findFirst();

        System.out.println(payCardOptional.get().getId());

        return "ok";
    }

    /**
     * 作用：二维码识别（图片）
     * 作者：Tiddler
     * 时间：2018-08-2018/8/31 16：23
     * 类名：QRCodeTools
     **/
        /**
         * 解析二维码解析,此方法是解析Base64格式二维码图片
         * baseStr:base64字符串,data:image/png;base64开头的
         */
        public static String deEncodeByBase64(String baseStr) {
            String content = null;
            BufferedImage image;
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b=null;
            try {
                int i = baseStr.indexOf("data:image/png;base64,");
                baseStr = baseStr.substring(i+"data:image/png;base64,".length());//去掉base64图片的data:image/png;base64,部分才能转换为byte[]

                b = decoder.decodeBuffer(baseStr);//baseStr转byte[]
                ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(b);//byte[] 转BufferedImage
                image = ImageIO.read(byteArrayInputStream);
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                com.google.zxing.Result  result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
                System.out.println("图片中内容：  ");
                System.out.println("content： " + result.getText());
                content = result.getText();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
            return content;
        }
        /**
         * 解析二维码,此方法解析一个路径的二维码图片
         * path:图片路径
         */
        public static String deEncodeByPath(String path) {
            String content = null;
            BufferedImage image;
            try {
                image = ImageIO.read(new File(path));
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                com.google.zxing.Result  result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
                System.out.println("图片中内容：  ");
                System.out.println("content： " + result.getText());
                content = result.getText();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
            return content;
        }

}
